/**
 * @file   MainWindow.cpp
 * @author Djuro Drljaca (djurodrljaca@gmail.com)
 * @date   2013-05-03
 * @brief  DataBus Server Test Application Main Window.
 *
 * Copyright (C) 2013  Djuro Drljaca <djurodrljaca@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::MainWindow),
      m_dataBusServer(parent)
{
    // Setup GUI
    ui->setupUi(this);

    // Add client list model to registered clients list view
    ui->registeredClients_listView->setModel(m_dataBusServer.getClientListModel());

    // Show the selected client when user selects it in the GUI
    connect(ui->registeredClients_listView, SIGNAL(activated(QModelIndex)),
            this, SLOT(showSelectedClientInfo(QModelIndex)));

    // Connect Start Server and Stop Server buttons to DataBus Server
    connect(ui->startServer_pushButton, SIGNAL(clicked()),
            this, SLOT(startServer()));

    connect(ui->stopServer_pushButton, SIGNAL(clicked()),
            this, SLOT(stopServer()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showSelectedClientInfo(const QModelIndex index)
{
    // Get client
    const DataBus::Client * client = m_dataBusServer.getClient(index.row());

    if (client == 0)
    {
        return;
    }

    // Display Client ID
    ui->clientId_lineEdit->setText(QString::number(client->getClientId()));

    // Display Activity Timeout
    ui->activityTimeout_lineEdit->setText(QString::number(client->getActivityTimeout()));

    // Display Ping Response Timeout
    ui->pingResponseTimeout_lineEdit->setText(QString::number(client->getPingResponseTimeout()));

    // Display Ping Response Timeout
    ui->pingRetryCount_lineEdit->setText(QString::number(client->getPingRetryCount()));
}

void MainWindow::startServer()
{
    quint16 port = (quint16)ui->tcpPort_spinBox->value();

    if (m_dataBusServer.start(port))
    {
        ui->startServer_pushButton->setEnabled(false);
        ui->stopServer_pushButton->setEnabled(true);
    }
}

void MainWindow::stopServer()
{
    m_dataBusServer.stop();
    ui->startServer_pushButton->setEnabled(true);
    ui->stopServer_pushButton->setEnabled(false);
}
